/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.resource.endpoint;

import io.swagger.annotations.Api;
import lombok.SneakyThrows;
import org.springblade.core.launch.constant.AppConstant;
import org.springblade.core.oss.model.BladeFile;
import org.springblade.core.tenant.annotation.NonDS;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.FileUtil;
import org.springblade.modules.resource.entity.LocalAttach;
import org.springblade.modules.resource.entity.LocalOption;
import org.springblade.modules.resource.service.ILocalAttachService;
import org.springblade.modules.resource.service.ILocalOptionService;
import org.springblade.modules.resource.utils.FileUploadUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 对象存储端点
 *
 * @author Chill
 */
@NonDS
@RestController
@Api(value = "本地存储端点", tags = "本地存储端点")
@RequestMapping(AppConstant.APPLICATION_RESOURCE_NAME + "/local/endpoint")
public class LocalEndpoint {

	@Resource
	private ILocalOptionService localOptionService;

	@Resource
	private ILocalAttachService localAttachService;

	@Value("${blade.file.upload-path}")
	private String uploadPath;

	@Value("${blade.file.upload-domain}")
	private String uploadDomain;

	@Value("${blade.file.upload-prefix}")
	private String uploadPrefix;

//	/**
//	 * 上傳接口測試
//	 */
//	@PostMapping(value = "/upload-file/em")
//	public R CommonUploadFile(MultipartFile file) {
//		try {
//			//获取上传目的文件夹路径
//			LocalOption defaultOption = localOptionService.getDefaultOption();
//			//拼接最终路径
//			String finalPath = uploadPath + "/upload" + defaultOption.getUploadPath();
//			//執行上傳操作
//			String uploadFileUrl = FileUploadUtils.upload(finalPath, file);
//			uploadFileUrl = uploadFileUrl.replace(uploadPath, uploadPrefix);
//			System.out.println("uploadFileUrl==" + uploadFileUrl);
//			///http://localhost/enterprise-bladex/ + profile/upload/2021/08/02/165e27b58680c3db2ec010e505ab9337.jpg
//			return R.success(ResultCode.SUCCESS, "111");
//		} catch (Exception e) {
//			e.printStackTrace();
//			return R.fail(e.getMessage());
//		}
//	}


	/**
	 * 上传接口，返回上传地址
	 */
	@PostMapping(value = "/arrayFileUpload-file")
	public R<Map<String, Object>> arrayFileUpload(MultipartFile file) {
		try {
			//获取上传目的文件夹名称
			LocalOption defaultOption = localOptionService.getDefaultOption();
			//拼接最终路径
			String finalPath = uploadPath + "/upload" + defaultOption.getUploadPath();
			//執行上傳操作
			String uploadFileUrl = FileUploadUtils.upload(finalPath, file);
			uploadFileUrl = uploadFileUrl.replace(uploadPath, uploadPrefix);
			System.out.println("uploadFileUrl==" + uploadFileUrl);
			///http://localhost/enterprise-bladex/ + profile/upload/2021/08/02/165e27b58680c3db2ec010e505ab9337.jpg

			Map<String, Object> resMap = new HashMap<>();
			resMap.put("url", uploadDomain + uploadFileUrl);
			resMap.put("name", uploadFileUrl.substring(uploadFileUrl.lastIndexOf("/") + 1));
			return R.data(resMap);
		} catch (Exception e) {
			e.printStackTrace();
			return R.fail(e.getMessage());
		}
	}


	/**
	 * 上传文件并保存至本地附件表
	 *
	 * @param file 文件
	 * @return ObjectStat
	 */
	@SneakyThrows
	@PostMapping("/upload-file")
	public R<BladeFile> putFileAttach(@RequestParam MultipartFile file) {
		//文件原名
		String originalFileName = file.getOriginalFilename();
		//文件大小（kb）
		long size = file.getSize() / 1024;
		//获取上传目的文件夹路径
		LocalOption defaultOption = localOptionService.getDefaultOption();
		//拼接最终路径
		String finalPath = uploadPath + "/upload" + defaultOption.getUploadPath();
		//執行上傳操作返回鏈接
		String uploadFileUrl = FileUploadUtils.upload(finalPath, file);
		uploadFileUrl = uploadFileUrl.replace(uploadPath, uploadPrefix);
		//上傳后的名稱
		String fileName = uploadFileUrl.substring(uploadFileUrl.lastIndexOf("/") + 1);

		LocalAttach attach = new LocalAttach();
		String fileExtension = FileUtil.getFileExtension(fileName);
		attach.setAttachSize(size);
		attach.setExtension(fileExtension);
		attach.setName(fileName);
		attach.setOriginalName(originalFileName);
		attach.setLink(uploadDomain + uploadFileUrl);
		attach.setDomain(uploadDomain);
		return R.status(this.localAttachService.save(attach));
	}


}



